package com.lp.sys.controller.base;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iframework.commons.domain.enums.HttpStatusCode;
import org.iframework.commons.domain.enums.RecordStatus;
import org.iframework.commons.domain.order.Order;
import org.iframework.commons.domain.order.OrderImpl;
import org.iframework.commons.domain.pager.Pager;
import org.iframework.commons.domain.pager.PagerImpl;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.context.BaseSpringContextSupport;
import org.iframework.support.spring.controller.BaseControllerSupport;
import org.iframework.support.spring.hibernate.model.BaseHibernateModelSupport;
import org.iframework.support.spring.hibernate.service.BaseServiceSupport;
import org.iframework.support.spring.validator.BaseFormValidator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.lp.business.domain.JsonResultModel;

/**
 * 基础控制器支持类
 * 
 * @author lipeng
 * @param <M> 模型对象
 * @param <PK> 主键对象
 */
public abstract class BaseController<M extends BaseHibernateModelSupport, PK extends Serializable> extends BaseControllerSupport {

	/**
	 * 基本业务支持服务接口（如果需要自定义方法时可以调用该接口下的方法做增删改查操作）
	 */
	public BaseServiceSupport<M, PK> baseService;

	/**
	 * 设置基本业务支持服务接口（如果需要用到父类的方法，则需要在子类中注入操作的业务接口）
	 * 
	 * @param baseService 基本服务对象
	 */
	public void setBaseServiceSupport(BaseServiceSupport<M, PK> baseService) {
		this.baseService = baseService;
	}

	/**
	 * 获取验证支持类<br/>
	 * 
	 * @param model 模型对象
	 * @return BaseFormValidator<M, PK> 基本验证对象
	 */
	@SuppressWarnings("unchecked")
	public BaseFormValidator<M, PK> getBaseValidator(M model) {
		BaseFormValidator<M, PK> baseFormValidator = (BaseFormValidator<M, PK>) BaseSpringContextSupport.getApplicationContext().getBean(model.getModelName() + "FormValidator");
		return baseFormValidator;
	}

	
	/**
	 * 进入列表页入口（默认）
	 * 
	 * @param request 其中如果有分页信息则程序自动分析绑定
	 * @param model 模型对象（查询的模型对象）
	 * @return ModelAndView 视图页面
	 */
	@RequestMapping(value = "index", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, M model) {
		ModelAndView modelAndView = new ModelAndView(model.getModelName() + "/index");
		return modelAndView;
	} 
	
	/**
	 * 进入添加页面入口（默认）<br/>
	 * 
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param model 模型对象
	 * @return ModelAndView 视图页面
	 */
	@RequestMapping(value = "add", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response, M model) {
		ModelAndView modelAndView = new ModelAndView(model.getModelName() + "/add");
		return modelAndView;
	}

	/**
	 * 进入编辑页面入口（默认）<br/>
	 * 
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param model 模型对象
	 * @return ModelAndView 视图页面
	 */
	@RequestMapping(value = "edit", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, M model) {
		ModelAndView modelAndView = new ModelAndView(model.getModelName() + "/edit");
		if (model != null && model.getId() != null) {
			if (this.baseService.load(model)) {
				modelAndView.addObject("model", model);
			}
		}
		return modelAndView;
	}
	
	/**
	 * 进入详情页入口（默认）
	 * 
	 * @param request 请求对象
	 * @param model 模型对象（查询的模型对象，模型记录ID主键必须）
	 * @return ModelAndView 视图页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "baseDetail", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView baseDetail(HttpServletRequest request, M model) {
		ModelAndView modelAndView = new ModelAndView(model.getModelName() + "/detail");
		modelAndView.addObject("model", this.baseService.get((PK) model.getId()));
		return modelAndView;
	}
	
	/**
	 * 加载分页列表数据
	 */
	@RequestMapping(value = "baseList", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView baseList(HttpServletRequest request, HttpServletResponse response, M model) {
		ModelAndView modelAndView = new ModelAndView(model.getModelName() + "/pageList");
		model.setStatus(RecordStatus.AVAILABLE);
		Pager pager = this.getPager(request);
		Order order = this.getOrder(request);
		List<M> models = this.baseService.findByModel(model, order, pager);
		modelAndView.addObject("models", models);
		modelAndView.addObject("page", pager);

		return modelAndView;
	}
	
	/**
	 * 进行保存操作
	 */
	@RequestMapping(value = "baseSave", method = { RequestMethod.POST, RequestMethod.GET })
	public void baseSave(HttpServletRequest request, HttpServletResponse response, M model) {
		try {
			if (V.isNotEmpty(this.baseService.save(model))) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "新建保存操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新建保存操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		} 
	}

	/**
	 * 进行更新操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "baseUpdate", method = { RequestMethod.POST, RequestMethod.GET })
	public void baseUpdate(HttpServletRequest request, HttpServletResponse response, M model) {
		//校验是否传入id信息
		if (V.isEmpty(model.getId())) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "ID必须填写").toSysJsonString(), response);
			return;
		}
		//校验是否存在相应数据
		if (V.isEmpty(this.baseService.get((PK) model.getId()))) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "找不到需要更新的数据").toSysJsonString(), response);
			return;
		}
		
		try {
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新修改操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新修改操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 进行批量删除操作
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "baseBatchDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public void baseBatchDelete(HttpServletRequest request, HttpServletResponse response) {
		//1.执行必填校验
		String[] ids = request.getParameterValues("ids[]");
		if (V.isEmpty(ids)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "请选择需要删除的信息").toSysJsonString(), response);
			return;
		}
		//2.执行删除
		try {
			Collection<M> models = new ArrayList<M>();
			for (String id : ids) {
				//校验是否有此id的数据
				M model = this.baseService.get((PK) id);
				if(V.isEmpty(model)){
					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "删除失败，未找到需要删除的数据").toSysJsonString(), response);
					return;
				}
				models.add(model);
			}
			if(this.baseService.deleteAllVirtual(models)){
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "批量删除操作成功").toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "批量删除操作失败").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试。").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 进行删除操作（默认虚拟删除）<br/>
	 * 
	 * @param request  请求对象
	 * @param response 响应对象
	 * @param model 模型对象
	 */
	@RequestMapping(value = "baseDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public void baseDelete(HttpServletRequest request, HttpServletResponse response, M model) {
		try {
			model.setStatus(RecordStatus.DELETE);
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "记录删除成功",model.getModelName()).toSysJsonString(), response);
				return;
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "记录删除失败","").toSysJsonString(), response);
				return;
			}
		} catch (Exception e) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，记录删除失败").toSysJsonString(), response);
			return;
		}
	}
	
	/**
	 * 根据request获取基本分页模型信息
	 * 
	 * @param request 请求对象
	 * @return Pager 分页模型
	 */
	protected Pager getPager(HttpServletRequest request) {
		Pager pager = new PagerImpl(1,10);
		try {
			int page = V.isEmpty(request.getParameter("page"))?1:Integer.parseInt(request.getParameter("page"));
			int pageSize = V.isEmpty(request.getParameter("rows"))?10:Integer.parseInt(request.getParameter("rows"));
			pager = new PagerImpl(page,pageSize);
		} catch (Exception e) {
			L.e(e.getMessage(), e);
		}
		return pager;
	}
	
	/**
	 * 根据request获取基本排序模型信息
	 * 
	 * @param request 请求对象
	 * @return Order 排序模型
	 */
	protected Order getOrder(HttpServletRequest request) {
		Order order = new OrderImpl("createTime","desc");
		try{
			String orderField = request.getParameter("sort");
			String orderDirection = request.getParameter("order");
			if(V.isNotEmpty(orderField)&&V.isNotEmpty(orderDirection)){
				order = new OrderImpl(orderField, orderDirection);
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
		}
		return order;
	}

}

